<template>
  <div ref="chartsRef" style="width: 100%; height: 230px"></div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue'
import * as echarts from 'echarts'

const chartsRef = ref<HTMLDivElement>(null)

const chartsData = ref([
  { value: 0, name: '优' },
  { value: 0, name: '良' },
  { value: 0, name: '中' },
  { value: 0, name: '差' },
])

const defaultOptions = {
  legend: {
    top: 'bottom',
  },
  toolbox: {},
  series: [
    {
      name: 'Nightingale Chart',
      type: 'pie',
      radius: [60, 90],
      center: ['50%', '50%'],
      roseType: 'area',
      itemStyle: {
        borderRadius: 8,
      },
      data: [],
    },
  ],
}

const options = computed(() => ({
  ...defaultOptions,
  grid: {
    left: '10%',
    right: 0,
    bottom: 0,
  },
  series: [
    {
      ...defaultOptions.series[0],
      data: chartsData.value,
    },
  ],
}))

const charts = ref(null)

onMounted(() => {
  init()
})

const init = () => {
  initCharts()
}

const initCharts = () => {
  if (chartsRef?.value) {
    const chart = echarts.init(chartsRef.value)
    chart.setOption(options.value)
    charts.value = chart
    // 窗口变化自适应
    window.addEventListener('resize', handleResize)
  }
}

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

const handleResize = () => {
  charts.value?.resize()
}
</script>
